﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml;

public class SoccerAPI
    {

        public List<Match> GetUpcomingMatches(int seriesID)
        {

            List<Match> Upcoming = (List<Match>)Utilities.GetFromCache(seriesID + ":Upcoming");

            if (Upcoming == null)
            {
                Upcoming = new List<Match>();

                DOM Document = new DOM(GetWidgetUrl("cominginleague", seriesID));

                var TableRows = Document.Query("tr");
                char[] querystringSplitChar = { '=' };

                int RowCount = 0;
                foreach (XmlNode Row in TableRows)
                {
                    try
                    {
                        if (RowCount > 2)
                        {
                            var Columns = Row.SelectNodes("td");

                            Match match = new Match();
                            match.Time = DateTime.Parse(Columns.ValueOfIndex(0));
                            match.MatchName = Columns.ValueOfIndex(1);
                            string MatchURI = Columns[1].SelectSingleNode("a").GetAttributeValue("href");
                            match.ID = MatchURI.Split(querystringSplitChar).LastOrDefault().ToString();

                            PopulateMatchDetails(match);
                            Upcoming.Add(match);

                        }
                        RowCount = RowCount + 1;
                    }
                    catch (Exception ex)
                    {
                        
                    }
                }

                Utilities.InsertToCache(seriesID + ":Upcoming", Upcoming);

            }

            return Upcoming;

        }

        private string GetWidgetUrl(string widget,int seriesID)
        {
            string url;

            string BaseUrl = "http://svenskfotboll.se/widget.aspx?scr={0}&ftid={1}&b1=%23233446&f1=%23ffffff&b2=%23acbfda&f2=%23000000&b3=%23ffffff&f3=%23000000&b4=%23ececec&bo=%23dfdfdf&nbr=8&s={2}";

            switch (widget)
            {
                case "cominginleague":
                    url = string.Format(BaseUrl,"cominginleague",seriesID,"");
                    break;
                case "table":
                        url = string.Format(BaseUrl, widget, seriesID,2);
                    break;
                default :
                    url = "";
                    break;
            }

            return url;

        }

        public List<TeamResults> GetScoreTable(int seriesID)
        {

            List<TeamResults> ScoreTable = (List<TeamResults>)Utilities.GetFromCache(seriesID + ":Scores");

            if (ScoreTable == null)
            {

                ScoreTable = new List<TeamResults>();

                DOM Document = new DOM(GetWidgetUrl("table", seriesID));

                var TableRows = Document.Query("table//tr");

                int RowCount = 0;
                foreach (XmlNode Row in TableRows)
                {
                    if (RowCount > 2)
                    {
                        var Columns = Row.SelectNodes("td");

                        TeamResults score = new TeamResults();

                        score.TeamName = Columns.ValueOfIndex(0);

                        score.MatchesPlayed = Columns.ValueOfIndex(1);
                        score.MatchesWon = Columns.ValueOfIndex(2);
                        score.MatchesDraw = Columns.ValueOfIndex(3);
                        score.MatchesLost = Columns.ValueOfIndex(4);
                        score.GoalsMadeAndReceived = Columns.ValueOfIndex(5);
                        score.Difference = Columns.ValueOfIndex(6);
                        score.Points = Columns.ValueOfIndex(7);

                        ScoreTable.Add(score);
                    }
                    RowCount = RowCount + 1;
                }
                    Utilities.InsertToCache(seriesID + ":Scores", ScoreTable);
                }

            return ScoreTable;
        }

        private void PopulateMatchDetails(Match match)
        {

            DOM Document = new DOM("http://svenskfotboll.se/ovriga-serier/information/?widget=1&scr=result&fmid=" + match.ID);

            var DetailRows = Document.Query("table[@id='iMatchInfo']//tr");   
            match.Venue = DetailRows.GetCellValueByFirstColumn("Spelplats");
            match.Referee = DetailRows.GetCellValueByFirstColumn("Domare");
            match.AssistingReferee1 = DetailRows.GetCellValueByFirstColumn("Ass. domare 1");
            match.AssistingReferee2 = DetailRows.GetCellValueByFirstColumn("Ass. domare 2");

            if (match.Venue != "")
            {
                var VenueLocation = GeoCoder.GeoCodeAddress(match.Venue);
                if (VenueLocation != null)
                {
                    match.VenueLongitude = VenueLocation.Longitude;
                    match.VenueLatitude = VenueLocation.Latitude;
                }
            }

            var Logotypes = Document.Query("table[@class='clTblMatch']//img");

            if (Logotypes.Count > 1)
            {
                match.Team1Logo = "http://svenskfotboll.se" + Logotypes[0].GetAttributeValue("src");
                match.Team2Logo = "http://svenskfotboll.se" + Logotypes[1].GetAttributeValue("src");

                match.Team1Logo = match.Team1Logo.Replace("/width_125", "");
                match.Team2Logo = match.Team1Logo.Replace("/width_125", "");
            }

            var PlayerTables = Document.GetTableByHeader("Laguppställning");
            var SecondaryPlayerTables = Document.GetTableByHeader("Ersättare");

            if (PlayerTables.Count > 1)
            {
                match.Team1Players = GetPlayers(PlayerTables[0]);
                match.Team2Players = GetPlayers(PlayerTables[1]);
            }

            if (SecondaryPlayerTables.Count > 1)
            {
                match.Team1SecondaryPlayers = GetPlayers(SecondaryPlayerTables[0]);
                match.Team2SecondaryPlayers = GetPlayers(SecondaryPlayerTables[1]);
            }

            // To not flood their server
            System.Threading.Thread.Sleep(200);
            
        }

        private List<Player> GetPlayers(XmlNode sourceTable)
        {
            if (sourceTable == null) { return null; }
            List<Player> Players = new List<Player>();
            if (sourceTable != null)
            {
                var Rows = sourceTable.SelectNodes("tbody/tr");
                foreach (XmlNode row in Rows)
                {
                    var Cells = row.SelectNodes("td");
                    if (Cells.Count > 1)
                    {
                        Player player = new Player();
                        player.Name = Cells.ValueOfIndex(1);
                        Players.Add(player);
                    }
                }
            }
            return Players;
        }

        public List<Series> GetSeries()
        {
            List<Series> AllSeries = (List<Series>)Utilities.GetFromCache("AllSeries");

            if (AllSeries == null) {
                AllSeries = new List<Series>();
                DOM Document = new DOM("http://www.svenskfotboll.se");
                var Series = Document.Query("select[@id='ftid-stickybar']//option");
                foreach(XmlNode node in Series){
                    Series serie = new Series();
                    serie.ID = int.Parse(node.GetAttributeValue("value"));
                    serie.Name = node.InnerText;
                    AllSeries.Add(serie);
                }

               Utilities.InsertToCache("AllSeries", AllSeries);

            }

            return AllSeries;
        }

    }
